package com.example.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * json操作
 * @author wanglong
 * @date 2018年1月8日 下午8:24:07
 */
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper() {
        private static final long serialVersionUID = 6701401850011062291L;
        {
            setSerializationInclusion(JsonInclude.Include.NON_NULL);
            configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
    };

    /**
     * 对象转换为josn字符串
     * @author wanglong
     * @date 2018年1月8日 下午8:27:57
     * @param object
     * @return
     * @throws IOException
     */
    public static String toJsonString(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 对象转换为josn字符串
     * @author wanglong
     * @date 2018年1月8日 下午8:27:57
     * @param object
     * @return
     * @throws IOException
     */
    public static String toJsonString2(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * json转换为对象
     * @author wanglong
     * @date 2018年1月8日 下午8:30:28
     * @param content
     * @param clz
     * @return
     * @throws IOException
     */
    public static <T> T toObject(String content, Class<T> clz) {
        try {
            return objectMapper.readValue(content, clz);
        } catch (Exception e) {
            return null;
        }
    }


    //只支持单数据读取,不支持集合
    public  static JsonNode getValue(String json, String fieldName){
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            if (jsonNode == null ) {
                return null;
            }
            Optional<JsonNode> node = Optional.of(jsonNode);
            List<String> fieldNames = Arrays.asList(fieldName.split("/"));
            for (String name :fieldNames){
                if (StringUtils.isNotBlank(name)){
                    node = node.map(n->n.findValue(name));
                }
            }
            return node.isPresent()?node.get():null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null ;
    }

    public static Map<String, Object> objectToMap(Object obj) {
        return (Map)objectMapper.convertValue(obj, Map.class);
    }

    public static <T> T mapToObject(Map map, Class<T> tClass) {
        return objectMapper.convertValue(map, tClass);
    }

}
